package com.mall.common.controller;

import static com.mall.common.Constants.ROLE_VALUE_PREFIX;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mall.b2c.util.JsonDataGridHelper;
import com.mall.common.bean.Pager;
import com.mall.common.bean.SearchFilter;
import com.mall.common.domain.manage.Menu;
import com.mall.common.domain.manage.Operate;
import com.mall.common.domain.manage.Role;
import com.mall.common.exception.NoticeException;
import com.mall.common.service.MenuService;
import com.mall.common.service.OperateService;
import com.mall.common.service.RoleService;
import com.mall.common.util.Collections3;
import com.mall.common.util.ResponseUtils;
import com.mall.common.validation.annotation.RegexFieldValidator;
import com.mall.common.validation.annotation.RequiredFieldValidator;
import com.mall.common.validation.annotation.RequiredStringValidator;
import com.mall.common.validation.annotation.Validations;
import com.mall.common.web.Servlets;


/**
 * 后台Action类 - 菜单
 */
@Controller
@RequestMapping("/admin/system/role")
public class RoleController extends BaseController {

	@Resource private RoleService roleService;
	@Resource private MenuService menuService;
	@Resource private OperateService operateService;

	@RequestMapping(value="/tree", method=RequestMethod.GET)
	public String tree(){
		return "/admin/system/role/tree";
	}
	
	// 获取模块树
	@RequestMapping("/getPrivTree")
	@ResponseBody
	public String getPrivTree(HttpServletResponse response){
		List<Menu> menus = menuService.getAllMenus();
		List<Operate> operates = roleService.getAutOperate(null);
		
		JSONArray jarray = new JSONArray();
		JSONObject obj = new JSONObject();
		obj.put("name", "权限树");
		obj.put("open", true);
		jarray.add(obj);
		
		if(menus != null || operates != null){
			for (int i = 0; i < menus.size(); i++) {
				JSONObject jObj = menus.get(i).getJson();
				jObj.put("open", true);
				jarray.add(jObj);
			}
			
			for (int i = 0; i < operates.size(); i++) {
				JSONObject jObj = operates.get(i).getJson();
				jarray.add(jObj);
			}
		}
		
		return ResponseUtils.renderJSON(jarray, response);
	}
	
	// 列表
	@RequestMapping(value="/list", method=RequestMethod.GET)
	public String list() {
		return "/admin/system/role/list";
	}

	@RequestMapping("/queryData")
	@ResponseBody
	public Pager queryData(Pager pager, HttpServletRequest request){
		Map<String, Object> filterParams = Servlets.getParametersStartingWith(request);
		List<SearchFilter> filters = SearchFilter.parse(filterParams);
		
		pager = roleService.findPage(pager, filters);
		return JsonDataGridHelper.createJSONData(pager);
	}

	@RequestMapping(value="/add", method=RequestMethod.GET)
	public String input(){
		return "/admin/system/role/input";
	}

	@RequestMapping(value="/edit", method=RequestMethod.GET)
	public String edit(Long id, Model model){
		Role role = roleService.find(id);
		model.addAttribute("role", role);
		return "/admin/system/role/input";
	}

	@Validations(
		requiredFields = {
			@RequiredFieldValidator(fieldName = "id", message = "id非法!")
		}
	)
	@RequestMapping("/priv")
	@ResponseBody
	public JSONObject priv(Long id){
		Long[] menuIds = null;
		Long[] operateIds = null;
		Role role = roleService.find(id);
		Set<Menu> menuSet = role.getMenuSet();
		Set<Operate> operateSet = role.getOperateSet();
		
		if(Collections3.isNotEmpty(menuSet)){
			menuIds = new Long[menuSet.size()];
			int i = 0;
			for (Iterator<Menu> iterator = menuSet.iterator(); iterator.hasNext();) {
				Menu menu = (Menu) iterator.next();
				menuIds[i] = menu.getId();
				i++;
			}
		}
		
		if(operateSet != null && operateSet.size() > 0){
			operateIds = new Long[operateSet.size()];
			int i = 0;
			for (Iterator<Operate> iterator = operateSet.iterator(); iterator.hasNext();) {
				Operate operate = (Operate) iterator.next();
				operateIds[i] = operate.getId();
				i++;
			}
		}

		JSONObject jobj = new JSONObject();
		jobj.put("menuIds", menuIds);
		jobj.put("operateIds", operateIds);
		return jobj;
	}

	@Validations(
		requiredFields = {
			@RequiredFieldValidator(fieldName = "ids", message = "ids非法!")
		}
	)
	@RequestMapping("/deleteRole")
	@ResponseBody
	public String deleteRole(Long[] ids, HttpServletResponse response) {
		roleService.remove(ids);
		return ResponseUtils.renderJSON(successMessage, response);
	}

	@Validations(
		requiredStrings = { 
			@RequiredStringValidator(fieldName = "name", message = "角色名称不能为空!"),
			@RequiredStringValidator(fieldName = "value", message = "角色标识不能为空!")
		},
		regexFields = {
				@RegexFieldValidator(fieldName="value", expression="^" + ROLE_VALUE_PREFIX + "\\w+$", message="角色标识必须以" + ROLE_VALUE_PREFIX + "为前缀")
		}
	)
	@RequestMapping("/save")
	@ResponseBody
	public String save(Role role, HttpServletResponse response){
		if(!roleService.isUnique("name", null, role.getName())){
			throw new NoticeException("角色名称重复");
		}
		if(!roleService.isUnique("value", null, role.getValue())){
			throw new NoticeException("角色标识重复");
		}
		roleService.persist(role);
		return ResponseUtils.renderJSON(successMessage, response);
	}

	@Validations(
		requiredFields = {
			@RequiredFieldValidator(fieldName = "id", message = "角色不存在!")
		},
		requiredStrings = { 
			@RequiredStringValidator(fieldName = "name", message = "名称不能为空!"),
			@RequiredStringValidator(fieldName = "value", message = "角色标识不能为空!")
		},
		regexFields = {
				@RegexFieldValidator(fieldName="value", expression="^" + ROLE_VALUE_PREFIX + "\\w+$", message="角色标识必须以" + ROLE_VALUE_PREFIX + "为前缀")
		}
	)
	@RequestMapping("/update")
	@ResponseBody
	public String update(Role role, HttpServletResponse response){
		Role current = roleService.find(role.getId());
		if(!roleService.isUnique("name", current.getName(), role.getName())){
			throw new NoticeException("角色名称重复");
		}
		if(!roleService.isUnique("value", current.getValue(), role.getValue())){
			throw new NoticeException("角色标识重复");
		}
		current.setName(role.getName());
		current.setValue(role.getValue());
		current.setDescription(role.getDescription());
		roleService.update(current);
		return ResponseUtils.renderJSON(successMessage, response);
	}

	@Validations(
		requiredFields = {
			@RequiredFieldValidator(fieldName = "id", message = "角色不存在!"),
			@RequiredFieldValidator(fieldName = "menuIds", message = "菜单ID不能为空!"),
			@RequiredFieldValidator(fieldName = "operateIds", message = "操作ID不能为空!")
		}
	)
	@RequestMapping("/editRoleMenu")
	@ResponseBody
	public String editRoleMenu(Long id, Long[] menuIds, Long[] operateIds, HttpServletResponse response){
		Role role = roleService.find(id);
		if(role == null){
			throw new NoticeException("角色不存在");
		}
		roleService.editRoleMenu(role, menuIds, operateIds);
		return ResponseUtils.renderJSON(successMessage, response);
	}
	
	// 是否已存在ajax验证
	@RequestMapping("/checkName")
	@ResponseBody
	public String checkName(Role role, String oldValue) {
		String newValue = role.getName();
		if (roleService.isUnique("name", oldValue, newValue)) {
			return "true";
		} else {
			return "false";
		}
	}
	
	// 是否已存在 ajax验证
	@RequestMapping("/checkValue")
	@ResponseBody
	public String checkValue(Role role, String oldValue) {
		String newValue = role.getValue();
		if (roleService.isUnique("value", oldValue, newValue)) {
			return "true";
		} else {
			return "false";
		}
	}

	@RequestMapping("/roleMenu")
	public String roleMenu(Boolean isEdit, Model model){
		model.addAttribute("isEdit", isEdit);
		return "/admin/system/role/roleMenu";
	}

}